﻿// Extensions Made Easy - Copyright 2012 by Jan Van der Haegen - All rights reserved, use for educational purposes only.

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using ExtensionsMadeEasy.ClientAPI.Commands;
using Microsoft.LightSwitch.Runtime.Shell.ViewModels.Commands;
using Microsoft.VisualStudio.ExtensibilityHosting;
using Microsoft.LightSwitch.Client;

namespace ExtensionsMadeEasy.Presentation.Commands
{
    [Export(typeof(IShellCommandGroupProvider))]
    public sealed class EasyCommandGroupProvider : IShellCommandGroupProvider
    {
        readonly System.Collections.Generic.IEnumerable<IEasyCommandExporter> exports2 = VsExportProviderService.GetExportedValues<IEasyCommandExporter>();
        readonly Dictionary<IEasyCommandExporter, EasyCommand> cachedCommands = new Dictionary<IEasyCommandExporter, EasyCommand>();


        public System.Collections.Generic.IEnumerable<IShellCommandGroup> GetShellCommandGroups(Microsoft.LightSwitch.Client.IScreenObject currentScreen)
        {
            IList<IShellCommandGroup> commandGroups = new List<IShellCommandGroup>();
            foreach (EasyCommandExporter command in this.exports2)
            {
                if (command.IsCommandActiveForScreen(currentScreen))
                {
                    EasyCommandGroup group = commandGroups.Where(x => x.DisplayName == command.GroupName).FirstOrDefault() as EasyCommandGroup;
                    if (group == null)
                    {
                        group = new EasyCommandGroup { DisplayName = command.GroupName };
                        commandGroups.Add(group);
                    }
                    group.AddCommand(getCommand(command, group, currentScreen));
                }
            }
            return commandGroups;
        }

        private EasyCommand getCommand(IEasyCommandExporter command, EasyCommandGroup group, IScreenObject currentScreen) {
            EasyCommand cmd;
            if (!cachedCommands.ContainsKey(command)) {
                cachedCommands.Add(command, new EasyCommand(command, group.Name));
            }
            cmd = cachedCommands[command];
            cmd.CurrentScreen = currentScreen;
            return cmd; 
        }
    }
}